<template>
  <div>
    <el-form style=" align-items: center; gap: 16px; margin-bottom: 20px;">
      <!-- 搜索 & 新增管理员 -->
      <el-input
          v-model="filters.name"
          placeholder="按姓名搜索"
          clearable
          @clear="fetchAdmins"
          @keyup.enter="fetchAdmins"
          style="width: 240px"
      >
        <template #append>
          <el-button @click="fetchAdmins">
            <el-icon>
              <Search/>
            </el-icon>
          </el-button>
        </template>
      </el-input>
      <el-button type="primary" @click="openCreateHousekeeperDialog" style="margin-left: 16px">
        新增健康管家
      </el-button>
    </el-form>

    <!-- 管理员表格 -->
    <el-table
        :data="admins"
        v-if="admins.length"
        border
        stripe
        style="width: 100%; margin-top: 16px"
    >
      <el-table-column type="index" label="序号" width="60"/>
      <el-table-column prop="adName" label="姓名"/>
      <el-table-column prop="phone" label="电话"/>
      <el-table-column label="服务对象">
        <template #default="{ row }">
          <el-button
              v-if="row.role === '健康管家'"
              size="small"
              type="primary"
              @click="openClientsDialog(row.adId)"
          >查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" @click="toEdit(row.adId)">编辑</el-button>
          <el-button size="small" type="danger" @click="onDelete(row.adId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-else class="empty">暂无数据</div>

    <!-- 管理员列表分页 -->
    <div class="pagination-container" style="margin-top: 20px; display: flex; justify-content: flex-end;">
      <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="adminPagination.total"
          v-model:current-page="adminPagination.current"
          v-model:page-size="adminPagination.size"
          :page-sizes="[6, 10, 20, 50]"
          @current-change="handleAdminPageChange"
          @size-change="handleAdminSizeChange"
      />
    </div>

    <!-- 新增/编辑健康管家 Dialog -->
    <el-dialog
        :title="isEditing ? '编辑健康管家' : '新增健康管家'"
        v-model="showEditDialog"
        width="480px"
        @close="resetForm"
        custom-class="admin-dialog"
    >
      <el-form
          :model="form"
          label-width="100px"
          class="admin-form"
          :rules="rules"
          ref="adminForm"
      >
        <el-form-item label="角色" style="width: 100%;">
          <el-select v-model="form.role" disabled style="width: 100%">
            <el-option label="健康管家" value="健康管家" />
          </el-select>
        </el-form-item>

        <!-- 自动密码规则提示 -->
        <div
            v-if="!isEditing && form.role"
            style="font-size: 12px; color:#409eff; margin: -8px 0 12px 100px;"
        >
          {{ form.role === '管理员'
            ? '密码将设为与账号一致'
            : '密码将设为手机号后6位' }}
        </div>

        <el-form-item label="姓名" prop="adName">
          <el-input v-model="form.adName" placeholder="请输入姓名"/>
        </el-form-item>
        <!-- 账号与电话同步，无单独账号输入 -->
        <el-form-item label="电话" prop="phone">
          <el-input
              v-model="form.phone"
              placeholder="请输入电话"
              @blur="syncPhoneAccount"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button size="medium" @click="showEditDialog = false">
            取消
          </el-button>
          <el-button size="medium" type="primary" @click="submitForm">
            {{ isEditing ? '保存' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 服务对象列表 Dialog -->
    <el-dialog
        title="服务对象列表"
        v-model="showClientsDialog"
        width="700px"
        @close="resetClientsPagination"
    >
      <el-table
          :data="clients"
          border
          stripe
          @selection-change="onUnassignSelectionChange"
          ref="clientsTable"
      >
        <!-- 多选列 -->
        <el-table-column type="selection" width="55"/>
        <!-- 原来的列保持不变 -->
        <el-table-column type="index" label="序号" width="60"/>
        <el-table-column prop="clientName" label="姓名"/>
        <el-table-column prop="clientPhone" label="电话"/>
        <el-table-column prop="clientType" label="类型"/>
        <!-- 可以把原来的“操作”列删掉或保留单个按钮备用 -->
      </el-table>

      <div style="text-align: right; margin-top: 12px;">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="clientPagination.total"
            v-model:current-page="clientPagination.current"
            v-model:page-size="clientPagination.size"
            :page-sizes="[5, 10, 20]"
            @current-change="handleClientPageChange"
            @size-change="handleClientSizeChange"
        />
      </div>
      <div class="dialog-footer" style="text-align: right; margin-top: 12px;">
        <el-button @click="showClientsDialog = false">关闭</el-button>
        <el-button
            type="danger"
            :disabled="!selectedUnassignIds.length"
            @click="confirmUnassign"
        >移除
        </el-button>
        <el-button type="primary" @click="openAssignDialog">
          增加服务对象
        </el-button>
      </div>
    </el-dialog>

    <!-- 添加服务对象 Dialog -->
    <el-dialog
        title="添加服务对象"
        v-model="showAssignDialog"
        width="700px"
        @close="resetAssignPagination"
    >
      <el-input
          v-model="assignFilters.name"
          placeholder="按姓名搜索"
          clearable
          @clear="fetchUnassigned"
          @keyup.enter="fetchUnassigned"
          style="width: 240px; margin-bottom: 12px"
      >
        <template #append>
          <el-button @click="fetchUnassigned">搜索</el-button>
        </template>
      </el-input>
      <el-table
          :data="unassignedClients"
          border
          stripe
          @selection-change="onSelectionChange"
          ref="assignTable"
      >
        <!-- 多选列 -->
        <el-table-column type="selection" width="55"/>
        <!-- 其他列保持不变 -->
        <el-table-column prop="clientName" label="姓名"/>
        <el-table-column prop="clientPhone" label="电话"/>
        <el-table-column prop="clientType" label="类型"/>
      </el-table>
      <div style="text-align: right; margin-top: 12px;">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="assignPagination.total"
            v-model:current-page="assignPagination.current"
            v-model:page-size="assignPagination.size"
            :page-sizes="[5, 10, 20]"
            @current-change="handleAssignPageChange"
            @size-change="handleAssignSizeChange"
        />
      </div>
      <div class="dialog-footer" style="text-align: right; margin-top: 12px;">
        <el-button @click="showAssignDialog = false">取消</el-button>
        <el-button
            type="primary"
            :disabled="!selectedClientIds.length"
            @click="confirmAssign"
        >确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Search} from '@element-plus/icons-vue'
import {
  listAdmins,
  createAdmin,
  updateAdmin,
  unassignClient,
  deleteAdmin,
  listClientsByAdmin
} from '@/api/apiList/admin'
import {
  listUnassignedCareClients,
  assignClientToAdmin
} from '@/api/apiList/client'

// 管理员列表 & 分页
const admins = ref([])
const filters = reactive({name: ''})
const adminPagination = reactive({current: 1, size: 10, total: 0})
const isRoleFixed = ref(false)

async function fetchAdmins() {
  try {
    // 传入固定的 “健康管家” 角色
    const data = await listAdmins(
        filters.name,
        adminPagination.current,
        adminPagination.size,
        '健康管家'
    )
    // 直接拿后端返回的数据
    admins.value = data.records
    adminPagination.total = data.total
  } catch {
    ElMessage.error('获取健康管家列表失败')
  }
}


function handleAdminPageChange(p) {
  adminPagination.current = p;
  fetchAdmins()
}

function handleAdminSizeChange(s) {
  adminPagination.size = s;
  adminPagination.current = 1;
  fetchAdmins()
}

const adminForm = ref(null)
// 创建/编辑管理员
const showEditDialog = ref(false)
const isEditing = ref(false)
const form = reactive({
  adId: null,
  adAccount: '',
  adPassword: '',
  adName: '',
  phone: '',
  role: ''
})
const rules = {
  phone: [
    {required: true, message: '请输入电话', trigger: 'blur'},
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '手机号格式不正确',
      trigger: 'blur'
    }
  ],
  adName: [{required: true, message: '请输入姓名', trigger: 'blur'}]
}
// 多选时保存所有选中的 clientId
const selectedClientIds = ref([])

function onSelectionChange(selection) {
  selectedClientIds.value = selection.map(item => item.clientId)
}

const selectedUnassignIds = ref([])

function onUnassignSelectionChange(selection) {
  selectedUnassignIds.value = selection.map(item => item.clientId)
}

// 通用新增
function openCreateDialog() {
  isEditing.value = false
  resetForm()
  isRoleFixed.value = false     // 允许选角色
  showEditDialog.value = true
}

// 专门新增健康管家
function openCreateHousekeeperDialog() {
  isEditing.value = false
  resetForm()
  form.role = '健康管家'
  showEditDialog.value = true
}

async function toEdit(id) {
  const admin = admins.value.find(a => a.adId === id)
  if (!admin) return ElMessage.error('未找到记录')
  isEditing.value = true
  Object.assign(form, admin)
  showEditDialog.value = true
}

function resetForm() {
  form.adId = null
  form.adAccount = ''
  form.adName = ''
  form.phone = ''
  form.role = '健康管家'
}

async function submitForm() {
  const valid = await adminForm.value.validate().catch(() => false)
  if (!valid) return
  try {
    let payload
    if (isEditing.value) {
      // 编辑时——不带密码字段，只更新姓名/电话/账号
      payload = {
        adId: form.adId,
        adName: form.adName,
        phone: form.phone,
        adAccount: form.phone,       // 账号同步电话
        role: form.role
      }
      await updateAdmin(payload)
    } else {
      // 新增时——带密码字段，初始化为手机号后6位
      payload = {
        adName: form.adName,
        phone: form.phone,
        adAccount: form.phone,
        adPassword: form.phone.slice(-6), // 默认密码
        role: form.role
      }
      await createAdmin(payload)
    }
    ElMessage.success(isEditing.value ? '保存成功' : '创建成功')
    showEditDialog.value = false
    fetchAdmins()
  } catch {
    ElMessage.error('操作失败')
  }
}

function syncPhoneAccount() {
  form.adAccount = form.phone
}

async function onDelete(id) {
  try {
    await ElMessageBox.confirm('确认删除？', '提示', {type: 'warning'})
    await deleteAdmin(id)
    ElMessage.success('删除成功')
    fetchAdmins()
  } catch {
  }
}

// 服务对象列表 & 分页
const showClientsDialog = ref(false)
const currentAdminId = ref(null)
const clients = ref([])
const assignTable = ref(null)
const clientPagination = reactive({current: 1, size: 10, total: 0})

async function openClientsDialog(adminId) {
  currentAdminId.value = adminId
  clientPagination.current = 1
  await fetchClients()
  showClientsDialog.value = true
}

async function fetchClients() {
  try {
    const data = await listClientsByAdmin(
        currentAdminId.value,
        clientPagination.current,
        clientPagination.size
    )
    clients.value = data.records
    clientPagination.total = data.total
  } catch {
    ElMessage.error('获取服务对象失败')
  }
}

function handleClientPageChange(p) {
  clientPagination.current = p;
  fetchClients()
}

function handleClientSizeChange(s) {
  clientPagination.size = s;
  clientPagination.current = 1;
  fetchClients()
}

async function confirmUnassign() {
  if (!selectedUnassignIds.value.length) return
  try {
    await ElMessageBox.confirm(
        `确认移除 ${selectedUnassignIds.value.length} 个服务对象？`,
        '提示',
        {type: 'warning'}
    )
    // 如果后端支持批量接口，直接调用；否则遍历调用
    await Promise.all(
        selectedUnassignIds.value.map(id =>
            unassignClient(id)
        )
    )
    ElMessage.success('移除成功')
    // 刷新列表
    fetchClients()
    // 清空选中
    selectedUnassignIds.value = []
    refs.clientsTable.clearSelection()
  } catch {
    // 用户取消或错误
  }
}

function resetClientsPagination() {
  clientPagination.current = 1;
  clientPagination.size = 10
  clientPagination.total = 0;
  clients.value = []
}

// 添加服务对象列表 & 分页
const showAssignDialog = ref(false)
const assignFilters = reactive({name: ''})
const unassignedClients = ref([])
const assignPagination = reactive({current: 1, size: 10, total: 0})
const selectedClientId = ref(null)

function openAssignDialog() {
  assignFilters.name = '';
  selectedClientId.value = null
  assignPagination.current = 1;
  fetchUnassigned()
  showAssignDialog.value = true
}

async function fetchUnassigned() {
  try {
    const data = await listUnassignedCareClients(
        assignFilters.name,
        assignPagination.current,
        assignPagination.size
    )
    unassignedClients.value = data.records
    assignPagination.total = data.total
  } catch {
    ElMessage.error('获取候选客户失败')
  }
}

function handleAssignPageChange(p) {
  assignPagination.current = p;
  fetchUnassigned()
}

function handleAssignSizeChange(s) {
  assignPagination.size = s;
  assignPagination.current = 1;
  fetchUnassigned()
}

function onSelectUnassigned(row) {
  selectedClientId.value = row.clientId
}

async function confirmAssign() {
  if (!selectedClientIds.value.length) return
  try {
    // 只包裹网络请求
    await Promise.all(
        selectedClientIds.value.map(id =>
            assignClientToAdmin(id, currentAdminId.value)
        )
    )
    ElMessage.success('添加成功')
  } catch (e) {
    // 只有当真正的请求失败才走这里
    return ElMessage.error('添加失败')
  }

  // 下面这部分放在 try 外，避免一处小错误也走到上面的 catch
  fetchClients()
  fetchUnassigned()
  selectedClientIds.value = []

  // clearSelection 也要做空值校验
  if (assignTable.value) {
    assignTable.value.clearSelection()
  }
  showAssignDialog.value = false
}

function resetAssignPagination() {
  assignPagination.current = 1;
  assignPagination.size = 10
  assignPagination.total = 0;
  unassignedClients.value = [];
  selectedClientId.value = null
}

onMounted(fetchAdmins)
</script>

<style scoped>
/* 搜索区域容器优化 */
.el-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  background-color: #f9f9f9;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
  margin-bottom: 20px;
}

/* 搜索输入框优化 */
.el-input {
  border-radius: 6px;
}

/* 按钮统一圆角 & 间距 */
.el-button {
  border-radius: 6px;
}
.el-button + .el-button {
  margin-left: 10px;
}

/* 表格样式改进 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

/* 空状态样式 */
.empty {
  text-align: center;
  color: #999;
  margin-top: 40px;
  font-size: 14px;
}

/* 分页容器美化 */
.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}
.dialog-footer {
  text-align: right;
  padding: 12px 40px 24px;
}
.dialog-footer .el-button {
  min-width: 100px;
}

/* 表单居中显示 */
.admin-form {
  max-width: 420px;
  margin: 0 auto;
}

/* 表格内按钮对齐间距 */
.el-table .el-button {
  margin-right: 8px;
}
.el-table .el-button:last-child {
  margin-right: 0;
}

</style>
